package cn.wolfcode.crm.exception;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class CRMExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public String handleException(Exception ex, Model model, HandlerMethod handlerMethod, HttpServletResponse response) throws Exception {
        //判断是否是ajax请求执行的方法
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            //是的话,响应回去json字符串
            response.setContentType("application/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult("操作失败,联系管理员,13888888888", false);
            response.getWriter().print(JSON.toJSONString(jsonResult));
            return null;
        }
        //同步请求的返回错误视图
        model.addAttribute("ex", ex);
        return "common/error";
    }
}
